<template>
  <Screen v-if="screening" />
  <Editor v-else-if="_isPC" />
  <Mobile v-else />
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useScreenStore, useMainStore, useSnapshotStore, useSlidesStore, useAskStore } from '@/store'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
import { deleteDiscardedDB } from '@/utils/database'
import { isPC } from './utils/common'
import http from './utils/http'
import { slides } from '@/mocks/slides'
import { message } from 'ant-design-vue'
import useCreateElement from '@/hooks/useCreateElement'
import useSlideHandler from '@/hooks/useSlideHandler'

import Editor from './views/Editor/index.vue'
import Screen from './views/Screen/index.vue'
import Mobile from './views/Mobile/index.vue'

const _isPC = isPC()

const mainStore = useMainStore()
const askStore = useAskStore()
const snapshotStore = useSnapshotStore()
const { databaseId } = storeToRefs(mainStore)
const { screening } = storeToRefs(useScreenStore())
const slidesStore = useSlidesStore()
const { createSlide } = useSlideHandler()

const { createImageElement } = useCreateElement()

if (process.env.NODE_ENV === 'production') {
  window.onbeforeunload = () => false
}

onMounted(async () => {
  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  mainStore.setAvailableFonts()
})

const insertImage = async (srcList:Array<string>, index:number) => {
  // 重置PPT下标
  slidesStore.updateSlideIndex(index)
  for (const src of srcList) {
    // 添加图片
    createImageElement(src)
    // 等一下确定之前的内容执行完毕
    await new Promise(resolve => setTimeout(resolve, 200))
  }
}

// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
window.addEventListener('unload', () => {
  const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []

  discardedDBList.push(databaseId.value)

  const newDiscardedDB = JSON.stringify(discardedDBList)
  localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
})

window.addEventListener('load', () => {
  const queryString = window.location.search
  const urlParams = new URLSearchParams(queryString)

  let user_type = ''
  const rootStr: string = localStorage.getItem('persist:root') || ''
  if (rootStr) {
    const rootInfo = JSON.parse(rootStr)
    const { user } = rootInfo
    const userInfo = user ? JSON.parse(user) : {}
    user_type = userInfo.type || ''
  }

  fetch('./config.json').then(result => result.json()).then(data => {
    const { hostApi, load_pdf_url, preserve_pdf_url, submit_pdf_url, get_trade_list_url, upload_image_url } = data

    const type = urlParams.get('url') || 'default'
    const record_id = urlParams.get('record_id') || '0'
    const group_id = urlParams.get('group_id') || '0'
    const sub_key = urlParams.get('sub_key') || '0'

    const channel = new BroadcastChannel('insertImage')
    channel.onmessage = ({ data: { key, type, srcList, index} }) => {
      if (key === sub_key) {
        // 等两秒, 强行等待界面组件加载完毕
        if (type === 'init') {
          setTimeout(() => {
            insertImage(srcList, index)
          }, 200)
        }
        else insertImage(srcList, index)
      }
    }
    channel.postMessage({ key: sub_key, status: 'loaded' })

    askStore.setObj({
      user_type, type, record_id, group_id, sub_key, hostApi,
      load_pdf_url: hostApi + load_pdf_url,
      preserve_pdf_url: hostApi + preserve_pdf_url,
      submit_pdf_url: hostApi + submit_pdf_url,
      get_trade_list_url: hostApi + get_trade_list_url,
      upload_image_url: hostApi + upload_image_url,
      tradeList: []
    })

    http.post(hostApi + load_pdf_url, {
      funcName: 'FetchPptInfo',
      options: { type, record_id, group_id, sub_key }
    }).then(rep => {
      const { data } = rep.data
      if (data && data.ppt_content) {
        const slidesContent = JSON.parse(data.ppt_content)
        slidesStore.setSlides(slidesContent || slides)
      }
      else slidesStore.setSlides(slides)
    })
    // slidesStore.setSlides(slides)
    // const tradeRes = http.get(hostApi + get_trade_list_url, {
    //   params: {
    //     trade_type: 2
    //   }
    // })
    //
    // tradeRes.then(rep => {
    //   const { data } = rep.data
    //   askStore.setTradeList(data)
    // })
  })

})
</script>

<style lang="scss">
#app {
  height: 100%;
}
</style>